#include "client.h"
#include<sys/socket.h>
#include<unistd.h>
#include<stdio.h>
#include<string.h>
#include<fcntl.h>
#include<my_header.h>
int uploadFile(int netfd, const char *filename)
{
	int fileFd = open(filename, O_RDONLY);
	if (fileFd == -1) {
		perror("open file error");
		return - 1;
	}
	struct stat statbuf;
	fstat(fileFd, &statbuf);
	off_t filesize = statbuf.st_size;

	train_t filetrain;
	filetrain._length = sizeof(filesize);
	memcpy(filetrain._data, &filesize, filetrain._length);
	send(netfd, &filetrain,
	     sizeof(filetrain._length) + 4 + filetrain._length, 0);
    printf("send file size:%ld\n", filesize);
	while (1) {
		ssize_t read_ret =
			read(fileFd, filetrain._data, sizeof(filetrain._data));
		if (read_ret <= 0)
			break;

		filetrain._length = read_ret;
		send(netfd, &filetrain,
		     sizeof(filetrain._length) + 4 + filetrain._length, 0);
	}

	filetrain._length = 0;
	filetrain.taskType= CMD_TYPE_TRANSFER_END;
	send(netfd, &filetrain, sizeof(filetrain._length) + 4, 0);
	close(fileFd);
	return 0;
}

// 客户端下载文件（从服务器接收）
int downloadFile(int netfd, const char *filename)
{
	int fileFd = open(filename, O_WRONLY | O_CREAT | O_TRUNC, 0666);
	if (fileFd == -1) {
		perror("open file error");
		return -1;
	}

	train_t filetrain;
	recv(netfd, &filetrain,
	     sizeof(filetrain._length) + 4 + filetrain._length, MSG_WAITALL);
	off_t filesize;
	memcpy(&filesize, filetrain._data, filetrain._length);

	while (1) {
		recv(netfd, &filetrain._length, sizeof(filetrain._length),
		     MSG_WAITALL);
		recv(netfd, &filetrain.taskType, sizeof(filetrain.taskType),
		     MSG_WAITALL);

		if (filetrain.taskType == CMD_TYPE_TRANSFER_END) {
			break;
		}

		recv(netfd, filetrain._data, filetrain._length, MSG_WAITALL);
		write(fileFd, filetrain._data, filetrain._length);
	}
	close(fileFd);
	return 0;
}
